/*
 * This file is part of the xOperator SPARQL/XMPP agent.
 * For further information see: http://xoperator.aksw.org
 * Copyright (C) 2007-2008  Jörg Unbehauen

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.aksw.xoperator.aiml;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import bitoflife.chatterbean.parser.AliceBotParserException;


/**
 * Offers methods for interaction with the AIML engine. Should be used for
 * all external classes as entry point.
 */
public class AimlFacade {
    private Log log = LogFactory.getLog(AimlFacade.class);
    private AliceBotFactory aBotFactory;
    private Map<String, AliceBotExternal> chat2BotMapping = new HashMap<String, AliceBotExternal>();

    public AimlFacade(AliceBotFactory botFactory) {
        super();
        aBotFactory = botFactory;
    }

    private AliceBotExternal getBot(Chat chat) {
        AliceBotExternal botToReturn = this.chat2BotMapping.get(chat.getThreadID()
                                                                    .substring(0,
                    4));

        if (botToReturn == null) {
            try {
                botToReturn = aBotFactory.getAliceBot();
                chat2BotMapping.put(chat.getThreadID().substring(0, 4),
                    botToReturn);
            } catch (AliceBotParserException e) {
                log.error("unable tow create chatbot: " + e);
            }
        }

        return botToReturn;
    }

    /**
     * Let the bot respond directly into a chat.
     *
     * @param chat DOCUMENT ME!
     * @param message DOCUMENT ME!
     */
    public void letTheBotRespond(Chat chat, Message message) {
        AliceBotExternal bot = getBot(chat);

        String answer = bot.respond(message.getBody(), chat, message);

        if ((answer != null) && (answer.length() > 0)) {
            try {
                chat.sendMessage(answer);
            } catch (XMPPException e) {
                log.error("Unable to reply: " + e);
            }
        }
    }
}
